package cn.buk.qms.config;

import cn.buk.qms.security.MyAuthenticationProvider;
import cn.buk.qms.security.MySessionManagementFilter;
import cn.buk.qms.security.MyUserDetailsServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

/**
 *
 * @author yfdai
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class WebSecurityConfig  {

    private static final Logger logger = LogManager.getLogger(WebSecurityConfig.class);

    private final MyUserDetailsServiceImpl userDetailsService;

    public WebSecurityConfig(MyUserDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public AuthenticationProvider authenticationProvider(MyUserDetailsServiceImpl myUserDetailsServiceImpl) {
        return new MyAuthenticationProvider(myUserDetailsServiceImpl);
    }

    @Bean
    public AuthenticationManager authManager(AuthenticationProvider authenticationProvider) {
        return new ProviderManager(authenticationProvider);
    }

    @Bean
    public MySessionManagementFilter mySessionManagementFilter() {
        return new MySessionManagementFilter();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {

        return http
                .addFilterAfter(mySessionManagementFilter(), SessionManagementFilter.class)
                .csrf(csrf -> {
                    csrf.disable();
                })
                .cors(cors -> cors.disable())
                .authorizeHttpRequests(auth -> {
                    auth.requestMatchers("/error/**").permitAll();
                    auth.requestMatchers("/api/auth/**").permitAll();
                    auth.requestMatchers("/checkLoginStatus").permitAll();
                    auth.requestMatchers("/captcha.do").permitAll();
                    auth.requestMatchers("/logout.do", "/ajaxLogin.do", "/register.do", "/sendResetPasswordSms.do", "/resetPassword.do").permitAll();
//                    auth.requestMatchers("/privileges").permitAll();
                    auth.anyRequest().authenticated();
                })
                .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
//                .oauth2ResourceServer((oauth2) -> oauth2.jwt((jwt) -> jwt.decoder(jwtDecoder())))
                .userDetailsService(userDetailsService)
//                .httpBasic(Customizer.withDefaults())
                .securityContext((securityContext) -> securityContext
                        .securityContextRepository(new DelegatingSecurityContextRepository(
                                new RequestAttributeSecurityContextRepository(),
                                new HttpSessionSecurityContextRepository()
                        ))
                )
                .build();
    }
//
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        logger.info("HttpSecurity http");
//        http
//                .addFilterAfter(mySessionManagementFilter(), SessionManagementFilter.class)
//                .csrf().disable()
//                .authorizeRequests()
//                .antMatchers("/").permitAll()
//                .antMatchers("/wx-service/{id}").permitAll()
//                .antMatchers("/ww/user").permitAll()
//                .antMatchers("/ww/{id}/receive").permitAll()
//                .antMatchers("/self-service/order/{id}").permitAll()
////                .antMatchers("/airpp/{id}/receive").permitAll()
//                .antMatchers("/weixinVerify").permitAll()
//
//                .antMatchers("/captcha/**", "/login", "/register", "/find-password", "/chklogin").permitAll()
//                .antMatchers("/searchTmcPolicy.do", "/getTmcFlightDetail.do", "/getWorkTime.do").permitAll()
//                .antMatchers("/processPnrDetail.do").permitAll()
//                .antMatchers("/alipayReturnUrl.do", "/alipayNotifyUrl.do").permitAll()
//                .antMatchers("/flights/rav", "/flights/tgq").permitAll()
//
//                .antMatchers("/pay/wx/notify", "/pay/ali/notify", "/pay/rates", "/pay/domain").permitAll()
//                .antMatchers("/weixin/getOpenId", "/weixin/getUserInfo", "/weixin/jssdk_config").permitAll()
//                .antMatchers("/orders/createFlightOrder").permitAll()
//                .antMatchers("/material/{id}", "/material/{id}/play/**").permitAll()
//                .antMatchers("/group/list", "/group/all", "/group/{id}").permitAll()
//                .antMatchers("/trip/list", "/trip/{id}").permitAll()
//
//                .antMatchers(HttpMethod.GET, "/article/{id}").permitAll()
//                .antMatchers(HttpMethod.POST, "/login").permitAll()
//                .antMatchers("/sms/{id}/receive").permitAll()
//                .antMatchers("/public/**").permitAll()
//                .antMatchers("/data/airports").permitAll()
//                .antMatchers("/orders/**", "/psgs/**").authenticated()
//                .antMatchers("/admin/**").hasAnyAuthority(RoleInfo.ROLE_ADMIN, RoleInfo.ROLE_DATA_ADMIN)
//                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
//                .anyRequest().authenticated();
//    }
    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
